package com.pro.servlet.admin;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import com.pro.util.BaseServlet;
import com.pro.util.Result;

/**
 * Servlet implementation class ImageServlet
 */
public class ImageServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
       
	public void upload(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
		// 我们把数据输出到页面上
				PrintWriter printWriter = response.getWriter();
				
				SmartUpload smartUpload = new SmartUpload();
				// 2.设置字符集
				smartUpload.setCharset("utf-8");
				// 3.初始化
				smartUpload.initialize(getServletConfig(), request, response);
				try {
					// 4.上传文件
					smartUpload.upload();
					// 5.保存文件到指定位置(save只提供路径，使用原文件名上传文件)
					smartUpload.save("/upload");
					// 5.保存文件到指定位置(saveAs可以用指定名称上传文件)
					// 
					// 获取文件名
					String filename = smartUpload.getFiles().getFile(0).getFileName();
					//smartUpload.getFiles().getFile(0).saveAs("/upload/"+System.currentTimeMillis()+".jpg");
					printWriter.print(Result.toClient("upload/"+filename, "上传成功",true));
					} catch (SmartUploadException e) {
						printWriter.print(Result.toClient("图片过大", "上传失败",false));
					e.printStackTrace();
					}
				printWriter.flush();
				printWriter.close();
			}
}
